using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

[Serializable]
public class PlayerScore
{
    public int score;
    public string name;

    public PlayerScore(int score, string name)
    {
        this.score = score;
        this.name = name;
    }
}

[Serializable]
public class PlayerScoreData
{
    public List<PlayerScore> list;

    public PlayerScoreData()
    {
        list = new List<PlayerScore>();
    }
}

public class ScoreManager : Singleton<ScoreManager>
{

    private int score;

    protected override void Awake()
    {
        base.Awake();
    }

    private void OnEnable() {
        EventHandler.AddListener<int>(Events.HitBrick, UpdateScore);
    }

    private void OnDisable() {
        EventHandler.RemoveListener(Events.HitBrick);
    }
    
    public void UpdateScore(int score)
    {
        this.score += score;
        ScoreRecorder.UpdateScore();
    }

    public int GetCurrentScore() => score;

    public void ResetScore()
    {
        this.score = 0;
    }

    public const string SAVE_FILE_NAME = "player_score.json";
    public const string DEFAULT_NAME = "Null";

    private string playerName;

    public void UpdatePlayerName(string name)
    {
        playerName = name;
    }

    public PlayerScoreData LoadPlayerScoreData()
    {
        PlayerScoreData data = new PlayerScoreData();
        
        if(SaveSystem.SaveFileExit(SAVE_FILE_NAME))
        {
            data = SaveSystem.Load<PlayerScoreData>(SAVE_FILE_NAME);
        }
        else
        {
            while(data.list.Count < 10)
            {
                data.list.Add(new PlayerScore(0, DEFAULT_NAME));
            }
        }

        return data;
    }

    public void SavePlayerScoreData()
    {
        PlayerScoreData data = LoadPlayerScoreData();

        if(score > data.list[9].score)
        {
            data.list.RemoveAt(9);
            data.list.Add(new PlayerScore(score, (string.IsNullOrEmpty(playerName)?DEFAULT_NAME:playerName)));
            data.list.Sort((x, y) => y.score.CompareTo(x.score));
            SaveSystem.Save(SAVE_FILE_NAME, data);
        }
    }
}
